package com.tuzhi.security.service.impl;

import com.tuzhi.base.web.util.ServletUtil;
import com.tuzhi.common.domain.LoginUserBO;
import com.tuzhi.security.exception.LoginUserException;
import com.tuzhi.security.service.TokenStoreService;
import com.tuzhi.security.service.UserService;
import com.tuzhi.util.StringTzUtil;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserServiceImpl implements UserService {

    protected static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Value("${login.verification.code.switch:off}")
    protected String verificationCodeSwitch;

    @Autowired
    TokenServiceImpl tokenService;

    @Autowired
    TokenStoreService tokenStoreService;

    @Override
    public void verify(String userId, String pwd, String codeKey, String code) {

        if ("on".equalsIgnoreCase(verificationCodeSwitch)) {
            throw new LoginUserException(StringTzUtil.format("{}开启了验证码校验,需要自行实现！code={}", userId, code));
        }

        log.info("默认验证通过!");

    }

    @Override
    public LoginUserBO createLoginUser(String userId, String pwd) {
        try {
            // HttpServletRequest request = ServletUtil.getRequest();
            LoginUserBO loginUserBO = tokenService.createLoginUser(userId, null);
            return loginUserBO;
        } catch (Exception e) {
            throw new LoginUserException(StringTzUtil.format("{}创建LoginUser异常！err={}", userId,
                    ExceptionUtils.getRootCauseMessage(e)), e);
        }
    }

    @Override
    public void setData(LoginUserBO loginUserBO) {
        log.info("设置权限数据");
    }

    @Override
    public LoginUserBO login(String userId, String pwd, String codeKey, String code) {
        LoginUserBO loginUserBO = UserService.super.login(userId, pwd, codeKey, code);
        return loginUserBO;

    }

    @Override
    public void loginOut() {
        HttpServletRequest request = ServletUtil.getRequest();
        LoginUserBO loginUserBO = tokenService.getLoginUser(request);
        if (loginUserBO == null) {
            String token = tokenService.getToken(request);
            log.warn("登出请求时，在服务端找不到对应的用户信息，服务端己失效：{}", token);
            return;
        }
        String uuid = loginUserBO.getJti();
        tokenService.delLoginUser(uuid);
    }
}
